﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using FCMS.Entities;
using FCMS.Mvc.Security.Principal;
using FCMS.Extensions;

namespace FCMS.Mvc
{
    public class WebUtilities
    {
        private const string MIDDLE_TIER_KEY = "MT";

        /// <summary>
        /// Public static helper for accessing middle tier
        /// Used to share code with HttpHandlers which don't derive from Page.
        /// </summary>
        /// <param name="context">HttpContext</param>
        /// <returns>Middle tier object</returns>
        //public static MiddleTier GetMiddleTier(HttpContextBase context)
        //{
        //    if (context == null)
        //    {
        //        throw new ArgumentNullException("context");
        //    }

        //    MiddleTier mt = (MiddleTier)context.Application[MIDDLE_TIER_KEY];

        //    if (mt == null)
        //    {
        //        context.Application.Lock();
        //        mt = (MiddleTier)context.Application[MIDDLE_TIER_KEY];

        //        if (mt == null)
        //        {
        //            mt = new MiddleTier();
        //            context.Application.Add(MIDDLE_TIER_KEY, mt);
        //        }

        //        context.Application.UnLock();
        //    }

        //    return mt;
        //}

        public static UserIdentity GetIdentity(HttpContext context)
        {
            FormsAuthenticationTicket ticket;

            if (WebUtilities.GetIsAnonymousUser(context, out ticket))
            {
                return UserIdentity.Anonymous;
            }

            string[] parts = ticket.Name.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            return new UserIdentity(new User
            {
                UserID = parts[0].ToInt(),
                UserName = parts[1]
            });
        }

        public static void SetAuthCookie(User user, bool createPersistentCookie)
        {
            HttpCookie cookie = FormsAuthentication.GetAuthCookie(
                user.UserID + "|" + user.UserName,
                createPersistentCookie);

            cookie.Name = FormsAuthentication.FormsCookieName;
            cookie.HttpOnly = false;

            if (createPersistentCookie)
            {
                cookie.Expires = DateTime.Now.AddYears(30);
            }

            HttpContext.Current.Response.SetCookie(cookie);
        }

        public static void SignOut(HttpContextBase context)
        {
            var DetectiveCookie = new HttpCookie(FormsAuthentication.FormsCookieName) { Expires = DateTime.UtcNow.AddYears(-100) };
            context.Response.Cookies.Add(DetectiveCookie);
        }

        public static bool GetIsAnonymousUser(HttpContext context, out FormsAuthenticationTicket ticket)
        {
            string authToken;

            HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (cookie != null)
            {
                authToken = cookie.Value;
            }
            else
            {
                authToken = context.Request.Params["auth"];
            }

            if (authToken == null)
            {
                ticket = null;
                return true;
            }

            try
            {
                ticket = FormsAuthentication.Decrypt(authToken);
                return false;
            }
            catch (Exception)
            {
                ticket = null;
                return true;
            }
        }

    }
}
